from unittest.mock import patch
from library_test.base_test import BaseTest


class AnsibleModuleMocker:
    def __init__(self, params: dict):
        self.params = params


class BaseTestCheckUtil(BaseTest):

    @classmethod
    def get_module_path(cls):
        return "ascend_deployer.module_utils.check_library_utils"

    @classmethod
    def setUpClass(cls) -> None:
        super().setUpClass()
        from ascend_deployer.module_utils.check_library_utils.localhost_check import LocalhostCheck
        params = {'master_groups': "", 'master0_arch': "", 'worker0_arch': "", 'groups': ""}
        cls.localhost_check = LocalhostCheck(AnsibleModuleMocker(params), [])


class TestCheckUtils(BaseTestCheckUtil):
    def test_check_dl_diff_arch(self):
        def check_dl_diff_arch():
            self.localhost_check.master0_arch = 'aarch64'
            self.localhost_check.worker0_arch = 'x86_64'
            self.localhost_check.groups = {"other_build_image": "192.168.1.1"}
            self.localhost_check.check_dl_diff_arch()
            self.assertEqual([], self.localhost_check.error_messages)

            self.localhost_check.groups = {}
            self.localhost_check.check_dl_diff_arch()
            self.assertEqual(["Master and worker have different architectures. "
                              "The 'other_build_image' group is required but is empty."],
                             self.localhost_check.error_messages)
            self.localhost_check.groups = {"other_build_image": "192.168.1.1"}
        check_dl_diff_arch()

    @patch("os.path.isdir")
    @patch("os.listdir")
    @patch("os.path.isfile")
    def test_check_directory_and_files(self, mock_isfile, mock_listdir, mock_isdir):
        self.localhost_check.module.params.setdefault("mtos_sys_dir", "/fake/dir")
        mock_isdir.return_value = False
        self.localhost_check.check_mtos_kernel_devel_pkg()
        self.assertEqual(['Directory /fake/dir does not exist'], self.localhost_check.error_messages)
        self.localhost_check.error_messages = []

        mock_isdir.return_value = True
        self.localhost_check.check_mtos_kernel_devel_pkg()
        self.assertEqual(['MTOS needs to use the kernel-devel package that is not available on the '
                          'public network. If you need to use it, please download the dependencies and '
                          'replace kernel-devel with the '
                          'kernel-devel-5.10.0-218.0.0.mt20240808.560.mt2203sp4.aarch64.rpm package '
                          'after decompressing the image.'], self.localhost_check.error_messages)
        self.localhost_check.error_messages = []

        mock_listdir.side_effect = Exception("err msg")
        mock_isdir.return_value = True
        self.localhost_check.check_mtos_kernel_devel_pkg()
        self.assertEqual(['Error accessing directory /fake/dir: err msg'], self.localhost_check.error_messages)
